package com.stp.houbb;

import com.github.houbb.sensitive.word.api.IWordDeny;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义敏感词黑名单
 */
@Component
public class CustomWordDeny implements IWordDeny {
    @Override
    public List<String> deny() {
        //TODO 读取数据库或者读取文件
        List<String> wordList = new ArrayList<>();
        wordList.addAll(readSensitiveWordFile());
        return wordList;
    }

    /**
     * 读取敏感词文件
     * @return
     */
    private List<String> readSensitiveWordFile() {
        List<String> wordSet = null;
        //敏感词库
        try {
            ClassPathResource classPathResource = new ClassPathResource("static/sensitive.txt");
            InputStream inputStream = classPathResource.getInputStream();
            // 读取文件输入流
            InputStreamReader read = new InputStreamReader(inputStream,"GBK");
            // 文件是否是文件 和 是否存在
            wordSet = new ArrayList<>();
            // BufferedReader是包装类，先把字符读到缓存里，到缓存满了，再读入内存，提高了读的效率。
            BufferedReader br = new BufferedReader(read);
            String txt = null;
            // 读取文件，将文件内容放入到set中
            while ((txt = br.readLine()) != null) {
                wordSet.add(txt);
            }
            br.close();
            // 关闭文件流
            read.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return wordSet;
    }
}
